#include "Log.hpp"
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <thread>
#include <unistd.h>

using namespace LogModule;

std::string server_ip;
uint16_t server_port;
int sockfd;

bool running = true;

void Send()
{
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    inet_pton(AF_INET, server_ip.c_str(), &server.sin_addr);

    while (running)
    {
        // 1. 发消息
        std::string input;
        std::cout << "Please Enter# ";
        std::getline(std::cin, input); // 以\n为结束符

        sendto(sockfd, input.c_str(), input.size(), 0, (struct sockaddr *)&server, sizeof(server));
        // 发送的QUIT，要让所有在线用户知道
        if (input == "QUIT")
        {
            running = false;
            break;
        }
    }
}

void Receive()
{
    while (running)
    {
        // 2. 收消息
        char buf[128];
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        socklen_t len = sizeof(addr);
        int s = recvfrom(sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&addr, &len);
        if (s > 0)
        {
            buf[s] = 0;
            std::cerr << buf << std::endl;
        }
        else if (s == -1)
        {
            if (errno != EAGAIN && errno != EWOULDBLOCK)
            {
                LOG(LogLevel::ERROR) << "recvfrom error!";
            }
            // 超时后不退出循环，继续检查running（此时有机会退出）
        }
    }
}

// 利用命令行参数
// ./udpclient server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }

    server_ip = argv[1];
    server_port = std::stoi(argv[2]);

    // 1. 创建套接字
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket error!";
        exit(1);
    }
    LOG(LogLevel::INFO) << "socket success : " << sockfd;

    // 2. 给sockfd,绑定IP和端口号,OS自动绑定

    // 关键修正：设置接收超时（例如 3 秒 0 微秒），避免recvfrom无限阻塞
    struct timeval timeout;
    timeout.tv_sec = 3;  // 秒
    timeout.tv_usec = 0; // 微秒
    setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));

    std::thread t1(Send);
    std::thread t2(Receive);

    t1.join();
    t2.join();

    close(sockfd);
    return 0;
}
